<?php 

class shoppingCarControl extends CommonControl{

    public function index(){
        $this->assign('SESSION',$_SESSION);
        $this->display('car');
    }


    /**
     * 商品添加到购物车
     */
    public function add()
    {
        $st_id = q("st_id", "intval"); //库存id
        $db = M();
        //取得当前商品的属性名
        $sql = " SELECT ga.attr_value FROM hd_g_stock_attr AS sa JOIN hd_g_goods_attr AS ga
         ON sa.attr_value_av_id = ga.attr_value_av_id WHERE sa.stock_st_id=$st_id GROUP BY ga.attr_value_av_id";
        $attr = $db->query($sql);
        $attrStr = array();
        foreach ($attr as $a) {
            $attrStr[] = $a['attr_value'];
        }

        $sql = "SELECT g.gname,s.price,g.list_pic,s.stock FROM hd_g_stock AS s JOIN hd_g_goods AS g
        ON s.goods_gid=g.gid WHERE s.st_id=$st_id";

        $goods = $db->query($sql);
        $goods = current($goods);
        $goods['gname'] = $goods['gname'] . "&nbsp&nbsp&nbsp&nbsp" . implode("&nbsp&nbsp", $attrStr);
        $goods['gcount'] = q("gcount", "intval");
        $goods['st_id'] = $st_id;
        //创建购物车
        if (!isset($_SESSION['cart']['goods'])) {
            $_SESSION['cart'] = array();
            $_SESSION['cart']['goods'] = array();
        }
        //如果购物车中存在商品时，更改购买数量
        if (isset($_SESSION['cart']['goods'][$st_id])) {
            $_SESSION['cart']['goods'][$st_id]['gcount'] += $_GET['gcount'];
        } else {
            $_SESSION['cart']['goods'][$st_id] = $goods;
        }
        $_SESSION['cart']['goods'][$st_id]['gcount'] = min($_SESSION['cart']['goods'][$st_id]['gcount'], $goods['stock']);
        //汇总价格
        $total =0;//总价
        $count =0;//总商品数量
        foreach ($_SESSION['cart']['goods'] as $goods) {
            $total+= $goods['gcount'] * $goods['price'];
            $count+=$goods['gcount'];
        }
        $_SESSION['cart']['total_price']=$total;//总计
        $_SESSION['cart']['count']=$count;//总数量
        $num = count($_SESSION['cart']['goods']);
        $_SESSION['cart']['num'] = $num;
        $this->display("addCar");
    }


}





























 ?>